package cn.hfjava.kz.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hfjava.kz.config.properties.KzUploadProperties;
import cn.hfjava.kz.config.properties.MdUploadProperties;
import cn.hfjava.kz.entity.po.Templates;
import cn.hfjava.kz.entity.po.User;
import cn.hfjava.kz.exception.BizException;
import cn.hfjava.kz.service.TemplatesService;
import cn.hfjava.kz.service.UserService;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.file.FileNameUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.MultipartConfigElement;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/templates")
@Tag(name = "模板管理", description = "模板管理")
public class TemplatesController {
    @Resource
    private MdUploadProperties mdUploadProperties;

    @Resource
    private TemplatesService templatesService;

    @Resource
    private MultipartConfigElement multipartConfigElement;
    /**
     * 上传模板
     */
    private static final List<String> FILE_TYPE = Arrays.asList("doc", "docx","xlsx");

    @Operation(summary = "上传模板")
    @PostMapping(value = "/uploadMode", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public SaResult uploadModel(
            @RequestPart(name = "file", required = true) MultipartFile file) {
        // pdf、doc、docx  10MB
        if (file == null || file.getSize() == 0) {
            return SaResult.error("上传模板不能为空");
        }
        String fileName = "";
        fileName = file.getOriginalFilename();
        String[] split = fileName.split("\\.");
        String name = split[0];
        //String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1); // jpg
        String fileExt = FileNameUtil.extName(fileName); // jpg，不是.jpg
        Long fileSize = file.getSize();
        if (!FILE_TYPE.contains(fileExt)) {
            return SaResult.error("上传模板格式错误，仅支持(.doc,.dox,.xlsx)格式");
        }
        if (fileSize > multipartConfigElement.getMaxFileSize()) {
            return SaResult.error("上传模板大小不能超过10MB");
        }

        Integer loginId = StpUtil.getLoginIdAsInt();
//        User userEntity = userService.getById(loginId);

        String uploadPath = mdUploadProperties.getUploadPath();
//        LocalDateTime now = LocalDateTime.now();
//        String yearPath = String.valueOf(now.getYear());
//        String monthPath = String.valueOf(now.getMonthValue());
//        String dayPath = String.valueOf(now.getDayOfMonth());
//        String dirPath = yearPath + "/" + monthPath + "/" + dayPath + "/" + userEntity.getUsername() + "/";
        File dirFile = new File(uploadPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File destFile = new File(dirFile, fileName);
        Templates templates = new Templates();
        templates.setTemtype(fileExt);
        templates.setTemname(name);

        templates.setCreateddate(DateTime.now());
        templates.setUpdateddate(DateTime.now());
        templates.setTemaddress(destFile.toString());


        try {
            file.transferTo(destFile);
            String filePath = mdUploadProperties.getAssetsUrl()
                    .replaceFirst("\\*\\*", "") + fileName;
            String fileUrl = mdUploadProperties.getBaseUrl() + filePath;
            Map<String, String> modelMap = new HashMap<>();
            modelMap.put("url", fileUrl);
            modelMap.put("path", filePath);
            templates.setTemUrl(fileUrl);
            templatesService.save(templates);
            return SaResult.ok("上传模板成功").data(modelMap);
        } catch (IOException ex) {
            throw new BizException(500, "上传模板失败", ex);
        }
    }

    /**
     * 查询模板
     */

    @GetMapping("/listModels")
    @Operation(summary = "查询模板")
    public SaResult listModels() {
        List<Templates> list = templatesService.list();
        return SaResult.ok("查询模板成功").setData(list);
    }

    @DeleteMapping("/deleteModels")
    @Operation(summary = "删除模板")
    public SaResult deleteModels(@RequestParam("id") Integer id) {
        String msg = "";
        try {
            Templates byId = templatesService.getById(id);
            templatesService.removeById(byId);
            msg = "删除模板成功";
        } catch (Exception e) {
            msg = "删除模板失败";
        }
        return SaResult.ok(msg);

    }

    @Operation(summary = "动态生成word文档")
    @PostMapping("/dynamicWor")
    public SaResult dynamicWord(@RequestParam("path") String path) {
        String templatePath = "D:\\素材\\1.docx"; // 模板文件路径
        String fileName = System.currentTimeMillis() + ".docx";
        fileName = "D:\\素材" + fileName; // 输出文件名

        Map<String, Object> datas = new HashMap<>();
        datas.put("name", "测试文档");
//        datas.put("image", Pictures.ofUrl("http://example.com/image.png").size(100, 100).create());

        try {
            XWPFTemplate template = XWPFTemplate.compile(templatePath).render(datas);

            // 输出到文件系统
            FileOutputStream out = new FileOutputStream(fileName);
            template.write(out);
            out.flush();
            out.close();
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=export.docx");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 将生成的Word文档字节流封装为ResponseEntity


            // 或者直接返回响应
            // return ResponseEntity.ok(template.writeAsBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return SaResult.ok("导出成功");
    }


}
